// const mqtt = require('mqtt')
import mqtt from 'mqtt';
import dayjs from "dayjs";
import { connectOptions } from './use_mqtt.js'

let token = "11D166140179407C8A9C6DB8C9F85B69";
const userName = 'yh_zhongxyy ';
const userId = "1990";

const options = {
  clientId: 'mqttx_bbea5d63',
  username: 'thinker',
  password: '123456',
  // clientId,
  clean: true,
  connectTimeout: 4000,
  reconnectPeriod: 5000
}
const { protocol, host, port } = connectOptions

let connectUrl = `${protocol}://${host}:${port}`

const client = mqtt.connect(connectUrl, options)
console.log(connectUrl, '链接富能地址')

let dateTime = new Date().getTime()
// const imgUrl = `http://111.8.86.3:19126/api/auth/verificationCode/captcha-image/${dateTime}`
const optionList = [
  { fmAddress: '2111222166', meterId: '922343', code: 'XT200025' },
  { fmAddress: '2009210933', meterId: '139', code: 'XT200026' },
  { fmAddress: '2111222161', meterId: '922333', code: 'XT200028' },
  { fmAddress: '22020103208', meterId: '1282833', code: 'XT220498' },
]
setTimeout(() => {
  optionList.forEach((item) => {
    getUserList(item.fmAddress, item.meterId, item.code)
  })
}, 100);


let timer = setInterval(() => {
  optionList.forEach((item) => {
    getUserList(item.fmAddress, item.meterId, item.code)
  })
}, 5 * 60 * 1000);


setTimeout(() => {
  console.log(dayjs().format("YYYY-MM-DD HH:mm:ss"), ' ==== 关闭定时器。。。。')
  clearInterval(timer)
  client.end()
}, 2 * 60 * 1000);



const getUserList = (fmAddress, meterId, code) => {
  const params = new URLSearchParams();
  const startDate = dayjs().subtract(6, 'day').startOf('day').valueOf();
  const endOfDay = dayjs().endOf('day').valueOf(); // 获取今天的结束时间

  params.append("startDate", startDate.toString());
  params.append("endDate", endOfDay.toString());
  params.append("fmAddress", fmAddress);
  params.append("meterId", meterId);

  let url = 'http://111.8.86.3:19126/api/largeCustomer/operationManagement/meterRealTimeDataTable?' + params.toString();
  return fetch(url, {
    method: 'get',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'Accept': 'application/json, text/plain, */*',
      'Tw-Authorization': token,
      'Cookie': `userId=${userId}; userName=${userName}; TW-Authorization=${token};`
    }
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      if (data.code != 0) {
        console.log('获取数据错误，！！退出登录');
        logoutUser()
      } else {
        const liuliang = data.data.table[0].totalFlux
        const dateKey = 'T_' + data.data.table[0].readTime;
        let topic = 'third-party/xiangtanshuibiao/v2/up/report'

        let obj = {
          "deviceCode": code
        };
        obj[`${dateKey}`] = {
          "datas": {
            "liuliang": liuliang,
          }
        }
        const payload = [obj]
        const qos = 0
        client.on('connect', () => {
          console.log(`${code}: 连接成功。。。。。`)
          client.subscribe(topic, { qos }, (error) => {
            if (error) {
              console.log('subscribe error:', error)
              return
            }
            console.log(`${dayjs().format("YYYY-MM-DD HH:mm:ss")}----:发送消息至 topic: ${topic}`)
            client.publish(topic, JSON.stringify(payload), { qos }, (error) => {
              if (error) {
                console.error(error, '发送错误')
              }
            })
          })
        })
      }

    })
    .catch((error) => console.error('error:', error));
}






const logoutUser = async () => {
  const url = 'http://111.8.86.3:19126/api/auth/jwt/signOut'
  return fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'Accept': 'application/json, text/plain, */*',
      'Tw-Authorization': token,
      'Cookie': `userId=${userId}; userName=${userName}; TW-Authorization=${token};`
    }
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      token = ''
      if (data.code != 0) {
        console.log('退出登录失败，重新登录')
      } else {
        console.log('退出登录接口调用成功，重新登录')
      }
    })
    .catch((error) => console.error('error:', error));
};
